package com.cx.mall.search.service.impl;

import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch._types.query_dsl.RangeQuery;
import co.elastic.clients.json.JsonData;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cx.mall.common.entity.goods.model.Product;
import com.cx.mall.common.entity.search.SkuEs;
import com.cx.mall.search.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.client.elc.NativeQuery;
import org.springframework.data.elasticsearch.client.elc.NativeQueryBuilder;

import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ElasticsearchTemplate esTemplate;

    @Override
    public IPage<SkuEs> search(Product product) {
        try {
            log.info("开始构建搜索查询，参数: {}", product);
            
            //1.构建查询条件
            NativeQueryBuilder builder = NativeQuery.builder();
            ArrayList<Query> queryList = new ArrayList<>();
            
            //sku_name - 只有非空时才添加查询条件
            if (StringUtils.hasText(product.getSkuName())) {
                boolQuery(queryList, "sku_name", product.getSkuName());
            }
            
            //brand_id - 只有非空时才添加查询条件
            if (product.getBrandId() != null) {
                boolQuery(queryList, "brand_id", product.getBrandId());
            }
            
            //category_id - 只有非空时才添加查询条件
            if (product.getCategoryId() != null) {
                boolQuery(queryList, "category_id", product.getCategoryId());
            }
            //价格范围
            if(product.getRange() != null){
               rangeQuery(queryList, "price", product.getPrice().toString());
            }

            // 如果没有查询条件，使用match_all查询
            if (queryList.isEmpty()) {
                builder.withQuery(query -> query.matchAll(m -> m));
            } else {
                builder.withQuery(query -> query.bool(bool -> bool.must(queryList)));
            }
            
            builder.withSourceFilter(new FetchSourceFilter(
                new String[]{"sku_name","brand_name","category_name","sku_default_img","price","sku_id","spu_id","id"}, 
                null
            ));
            
            log.info("构建的查询条件: {}", builder.build().getQuery());
            
            //2.执行查询
            SearchHits<SkuEs> searchHits = esTemplate.search(builder.build(), SkuEs.class);
            log.info("搜索完成，命中数量: {}", searchHits.getTotalHits());

            List<SkuEs> skuEsList = searchHits.getSearchHits().stream()
                .map(SearchHit::getContent)
                .collect(Collectors.toList());
                
            //3.封装结果
            if(product.getCurrent() == null || product.getSize() == null){
                product.setCurrent(1);
                product.setSize(10);
            }

            IPage<SkuEs> ipage = new Page<>(product.getCurrent(), product.getSize());
            ipage.setRecords(skuEsList);
            ipage.setTotal(searchHits.getTotalHits());
            
            log.info("分页结果: 当前页={}, 页大小={}, 总记录数={}", 
                product.getCurrent(), product.getSize(), searchHits.getTotalHits());
                
            return ipage;
            
        } catch (Exception e) {
            log.error("搜索执行异常: {}", e.getMessage(), e);
            throw e;
        }
    }

    private Query rangeQuery(ArrayList<Query> queryList, String field, String value) {
        if (!StringUtils.hasText(value)) {
            return null;
        }

        RangeQuery rangeQuery = null;
        Query query = null;
        String[] split = value.split("-");
        
        try {
            if (split.length == 2) {
                // 范围查询：min-max
                String min = split[0].trim();
                String max = split[1].trim();
                
                if (StringUtils.hasText(min) && StringUtils.hasText(max)) {
                    // 两个值都存在：范围查询
                  rangeQuery=  RangeQuery.of(r -> r.field(field)
                            .gte(JsonData.of(min))
                            .lte(JsonData.of(max)));
                }
            } else {
                // 单个值：小于等于
              rangeQuery =  RangeQuery.of(r -> r.field(field)
                            .lte(JsonData.of(value.trim())));
            }
            
            if (rangeQuery != null) {
                 query = rangeQuery._toQuery();
                queryList.add(query);
                log.info("添加范围查询: field={}, value={}", field, value);
            }
            
        } catch (Exception e) {
            log.error("构建范围查询失败: field={}, value={}, error={}", field, value, e.getMessage());
        }
        
        return query;
    }

    private Query boolQuery(ArrayList<Query> queryList, String field, Object value) {
        if (value == null || (value instanceof String && !StringUtils.hasText((String) value))) {
            return null;
        }
        
        Query query = Query.of(q -> q.match(m -> m.field(field).query(String.valueOf(value))));
        queryList.add(query);
        return query;
    }
}
